/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Persistence;
import javax.persistence.Query;
import jpa.exceptions.NonexistentEntityException;

/**
 * @author Kelompok 3
 * Kelas ini berfungsi untuk mengelola fungsi yang dibutuhkan dalam modul Event
 * Fungsi tersebut dihungunkan dengan kelas entitas Event yang merupakan represntasi dari tabel events dalam database
 */
public class EventQuery {
    /* menghubungkan dengan database sesuai dengan 
     * konfigurasi pada persistence unit
     */

    public EventQuery() {
        emf = Persistence.createEntityManagerFactory("persistence");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    /* method yang digunakan untuk mengecek keberadaan satu baris 
     * pada tabel events berdasarkan parameter idEvent
     */
    public boolean checkEvent(Integer idEvent) {
        boolean result = false;
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("SELECT count(o) FROM Event AS o WHERE o.idEvent=:ie");
            q.setParameter("ie", idEvent);
            int jumlahEvent = ((Long) q.getSingleResult()).intValue();
            if (jumlahEvent > 0) {
                result = true;
            }
        } finally {
            if (em != null) {
                em.close();
            }
        }
        return result;
    }
    /* method yang digunakan untuk mengecek keberadaan satu baris 
     * pada tabel events berdasarkan parameter namaEvent
     */

    public boolean checkEvent(String namaEvent) {
        boolean result = false;
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("SELECT count(o) FROM Event AS o WHERE o.namaEvent=:ne");
            q.setParameter("ne", namaEvent);
            int jumlahEvent = ((Long) q.getSingleResult()).intValue();
            if (jumlahEvent > 0) {
                result = true;
            }
        } finally {
            if (em != null) {
                em.close();
            }
        }
        return result;
    }

    /* method untuk mengambil satu baris event 
     * berdasarkan parameter idEvent
     */
    public Event getEvent(Integer idEvent) {
        Event event = null;
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("SELECT object(o) FROM Event AS o WHERE o.idEvent=:ie");
            q.setParameter("ie", idEvent);
            event = (Event) q.getSingleResult();
        } finally {
            if (em != null) {
                em.close();
            }
        }
        return event;
    }
    /* method untuk mengambil satu baris event 
     * berdasarkan parameter namaEvent
     */

    public Event getEvent(String namaEvent) {
        Event event = null;
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("SELECT object(o) FROM Event AS o WHERE o.namaEvent=:ne");
            q.setParameter("ne", namaEvent);
            event = (Event) q.getSingleResult();
        } finally {
            if (em != null) {
                em.close();
            }
        }
        return event;
    }

    /* method untuk mengambil semua baris Event dari tabel events berdasarkan User yang sedang login
     */
    public List<Event> getMyEvents(User user) {
        List<Event> events = new ArrayList<Event>();

        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("SELECT object(o) FROM Event AS o WHERE o.idUser=:usr ORDER BY o.idEvent DESC");
            q.setParameter("usr", user);
            events = q.getResultList();

        } finally {
            if (em != null) {
                em.close();
            }
        }
        return events;
    }
    /* method untuk mengambil semua baris Event dari tabel events berdasarkan User yang sedang login
     */

    public List<Event> findEvents(String namaEvent) {
        List<Event> events = new ArrayList<Event>();
        EntityManager em = getEntityManager();
        StringTokenizer st = new StringTokenizer(namaEvent);
        String patternTemp = "";

        while (st.hasMoreTokens()) {
            String key = "'%" + st.nextToken() + "%'";
            patternTemp += "o.namaEvent LIKE " +key+ " OR ";
        }
        String pattern = patternTemp.substring(0, patternTemp.length()-3);
        try {
            Query q = em.createQuery("SELECT object(o) FROM Event AS o WHERE "+pattern+"ORDER BY o.idEvent DESC");
            //q.setParameter("pattern", pattern);
            events = q.getResultList();

        } finally {
            if (em != null) {
                em.close();
            }
        }
        return events;
    }

    /* method untuk mengambil semua baris Event dari tabel events diurutkan berdasarkan data yang terbaru
     */
    public List<Event> getAllEvents() {
        List<Event> events = new ArrayList<Event>();

        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("SELECT object(o) FROM Event AS o ORDER BY o.idEvent DESC");
            events = q.getResultList();

        } finally {
            if (em != null) {
                em.close();
            }
        }
        return events;
    }

    /* method untuk mengambil lima baris awal Event dari tabel events diurutkan berdasarkan data yang terbaru
     */
    public List<Event> getLimitedEvents() {
        List<Event> events = new ArrayList<Event>();

        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("SELECT object(o) FROM Event AS o ORDER BY o.idEvent DESC");
            q.setMaxResults(5);
            events = q.getResultList();

        } finally {
            if (em != null) {
                em.close();
            }
        }
        return events;
    }

    /* method untuk mengganti nilai atribut pada satu baris Event yang sudah ada pada tabel events
     */
    public void editEvent(Event event) {
        EntityManager em = getEntityManager();
        em.getTransaction().begin();
        try {
            em.merge(event);
            em.getTransaction().commit();
        } catch (Exception e) {
            em.getTransaction().rollback();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    /* method untuk memasukkan satu baris Event baru ke dalam tabel events
     */
    public void createEvent(Event event) {
        EntityManager em = getEntityManager();
        em.getTransaction().begin();
        try {
            em.persist(event);
            em.getTransaction().commit();
        } catch (Exception e) {
            em.getTransaction().rollback();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    /* method untuk menghapus satu baris Event pada tabel events
     */
    public void deleteEvent(int id) throws NonexistentEntityException {
        EntityManager em = getEntityManager();
        em.getTransaction().begin();
        try {
            Event event;
            try {
                event = em.getReference(Event.class, id);
                event.getIdEvent();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The event with id " + id + " no longer exists.", enfe);
            }
            em.remove(event);
            em.getTransaction().commit();
        } catch (Exception e) {
            em.getTransaction().rollback();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }
}
